package cn.qicaiwang.open.common.controller;



import cn.qicaiwang.open.common.entity.LoginUser;
import cn.qicaiwang.open.common.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author gaoxi
 * @Date 2021/6/29 10:12 下午
 **/
@Slf4j
public class BaseController {

    public String getCurrentUserId() {
        return SecurityUtil.getUserId();
    }

    public LoginUser getCurrentUser() {
        return SecurityUtil.getCurrentUser();
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                //通过两次异常的处理可以，绑定两次日期的格式
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = null;
                try {
                    date = format.parse(text);
                } catch (ParseException e) {
                    format = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        date = format.parse(text);
                    } catch (ParseException e1) {
                    }
                }
                setValue(date);
            }
        });
    }
}
